package com.bootx.job;

import com.bootx.config.DataUpdateHandler;
import com.bootx.entity.Lottery;
import com.bootx.entity.LotteryRecord;
import com.bootx.service.BetRecordService;
import com.bootx.service.LotteryRecordService;
import com.bootx.service.LotteryService;
import com.bootx.service.RedisService;
import com.bootx.util.DateUtils;
import com.bootx.util.lottery.LotteryUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author black
 */
@Component
public class LotteryJob {

    @Resource
    private LotteryRecordService lotteryRecordService;
    @Resource
    private JdbcTemplate jdbcTemplate;

    @Resource
    private RedisService redisService;
    @Resource
    private LotteryService lotteryService;

    /**
     * 获取最新一组的数据
     */
    @Scheduled(fixedRate = 1000*5)
    public void run(){
        List<Lottery> all = lotteryService.findAll();
        for (Lottery lottery : all) {
            //1. 获取到最新一条数据
            LotteryRecord lotteryRecord = lotteryRecordService.findLatestRecord(lottery.getCode());
            if(lotteryRecord!=null){
                //如果最新一条数据没有开奖号码。并且每预测，去预测
                if(StringUtils.isBlank(lotteryRecord.getDrawCode())){
                    // 需要预测
                    if(lotteryRecord.getPredictResult()==null || lotteryRecord.getPredictResult()==0){
                        lotteryRecordService.predict(lottery.getCode(),lotteryRecord.getSn());
                    }
                    if(lotteryRecord.getDrawTime().compareTo(new Date())<=0){
                        // 说明需要拉取数据,填充开奖信息
                        Map<String, LotteryRecord> data = LotteryUtils.getData(lottery.getCode(), 0);
                        LotteryRecord current = data.get("current");
                        lotteryRecordService.save(current);
                        if(StringUtils.isNotBlank(current.getDrawCode())){
                            LotteryRecord next = data.get("next");
                            if(next!=null){
                                lotteryRecordService.save(next);
                                lotteryRecordService.predict(lottery.getCode(),next.getSn());
                            }
                        }
                    }
                }else{
                    // 说明需要拉取下一条数据
                    Map<String, LotteryRecord> data = LotteryUtils.getData(lottery.getCode(), 0);
                    LotteryRecord next = data.get("next");
                    if(next!=null){
                        lotteryRecordService.save(next);
                        lotteryRecordService.predict(lottery.getCode(),next.getSn());
                    }
                }
                DataUpdateHandler.notifyUpdate("{\"type\":\"DATA_UPDATE\"}");
            }
        }
    }

    //@Scheduled(cron = "59 23 * * * *")
    //@Scheduled(fixedRate = 1000*60*60*8)
    public void history(){
        List<Map<String, Object>> maps1 = jdbcTemplate.queryForList("select code from lottery;");
        maps1.forEach(stringObjectMap -> {
            List<LotteryRecord> history = LotteryUtils.history(new Date(),Long.valueOf(stringObjectMap.get("code")+""));
            history.sort(Comparator.comparingLong(LotteryRecord::getSn));
            lotteryRecordService.batchSave(history);
            redisService.delete("lottery:"+stringObjectMap.get("code"));
        });
    }

    //@Scheduled(fixedRate = 1000*60*60*24)
    public void predict(){
        double amount1 = 0.0;
        double money = 800;
        Lottery lottery = lotteryService.find(1L);
        for (int j = 1; j < 10; j++) {
            lottery.setBalance(money);
            lotteryService.update(lottery);
            redisService.set("fail11111111111111111111111","0");
            Date date = DateUtils.getNextDay(-1*j);
            String dateStr = DateUtils.formatDateToString(date,"yyyy-MM-dd");
            List<Map<String, Object>> maps = jdbcTemplate.queryForList("select min(sn) `min`,max(sn) `max` from lotteryrecord where date=? and drawTime>=? and drawTime<=?", dateStr, dateStr + " " + lottery.getStartTime(), dateStr + " " + lottery.getEndTime());
            if(!maps.isEmpty() && !maps.getFirst().isEmpty() && maps.getFirst().get("min")!=null && maps.getFirst().get("max")!=null){
                for (long i = Long.parseLong(maps.getFirst().get("min")+""); i <= Long.parseLong(maps.getFirst().get("max")+""); i++) {
                    LotteryRecord lotteryRecord = lotteryRecordService.predict(10036L, i);
                    if(lotteryRecord==null){
                        amount1 = (amount1-money);
                        break;
                    }
                }
                lottery = lotteryService.find(1L);
                amount1 = (amount1+(lottery.getBalance()-money));
            }
        }
    }

    //@Scheduled(fixedRate = 1000*60*60*24)
    public void oldData(){
        List<Map<String, Object>> maps1 = jdbcTemplate.queryForList("select code from lottery;");
        maps1.forEach(stringObjectMap -> {
            for (int i = 0; i < 100; i++) {
                List<LotteryRecord> history = LotteryUtils.history(DateUtils.getNextDay(i*-1),Long.valueOf(stringObjectMap.get("code")+""));
                history.sort(Comparator.comparingLong(LotteryRecord::getSn));
                lotteryRecordService.batchSave(history);
                redisService.delete("lottery:"+stringObjectMap.get("code"));
            }
        });
    }

    /*@Scheduled(fixedRate = 1000*60)
    public void update(){
        Lottery lottery = lotteryService.find(1L);
        Integer sn = jdbcTemplate.queryForObject("select max(sn)%100000 from lotteryrecord where lotteryCode=?",Integer.class,lottery.getCode());
        Map<String,Object> data = new HashMap<>();
        data.put("sn",sn);
        data.put("type",System.currentTimeMillis()%2==0?"双":"单");
        data.put("num",(System.currentTimeMillis()%5)+"");
        data.put("money",lottery.getBaseBetMoney());
        data.put("send","1");
        redisService.set("sendInfo",JsonUtils.toJson(data));
    }*/

    /*@Scheduled(fixedRate = 1000*60*60*24)
    public void betRecord(){
        LotteryRecord bySn = lotteryRecordService.findBySn(13656030L);
        lotteryRecordService.addCache(bySn);
    }*/

    //@Scheduled(fixedRate = 1000*60*60*8)
    public void betConfig(){
        for (int i = 1; i <= 1151; i++) {
            jdbcTemplate.update("insert betconfig(createdDate, lastModifiedDate, version, orders, failType, winType) values (NOW(),NOW(),0,?,?,?)",i,1,1);
        }
    }
}
